<template>
    <el-tree-select v-model="form[option.prop]" :data="list" v-bind="option.element" @change="itemChange" />
</template>
<script setup lang="ts">
import { Ref, onBeforeMount, ref } from 'vue';
import http from '~/utils/httpRequest';
import useApp from '@admin/_find/store/app';
import { toPromise } from '@xuekl/cli-utils';
defineOptions({ name: 'XklTreeSelect' })
const props = defineProps(['form', 'option'])
const emit = defineEmits(['loaded', 'itemChange', 'update:label'])
const list: Ref<any[]> = ref([])
const appStore = useApp()

const { form, option } = props
const config = option.config


const handleData = (data) => {
    data.forEach(inner => {
        inner.value = inner[config.valueTarget || 'value']
        inner.label = inner[config.labelTarget || 'label']
        if (inner.children) {
            handleData(inner.children)
        }
    })
    return data
}

const itemChange = (val) => {
    if (Array.isArray(val)) {
        const values = val
        const items = list.value.filter(res => values.includes(res.value))
        const labels = items.map(res => res.label)
        if (items) {
            emit('update:label', labels)
            emit('itemChange', items)
        }
    } else {
        const item = list.value.find(res => res.value === val)
        if (item) {
            emit('update:label', item.label)
            emit('itemChange', item)
        }
    }
}

onBeforeMount(() => {
    //先读取缓存中的数据
    if (appStore.urlSelectData[config.url]) {
        list.value = appStore.urlSelectData[config.url]
        // 如果缓存中没有数据，可能是以为接口已经发出数据未返回，需要等待
        if (!list.value.length) {
            toPromise(() => appStore.urlSelectData[config.url]).then((vals) => {
                list.value = vals
                emit('loaded', list.value, (vals) => {
                    list.value = vals
                    appStore.urlSelectData[config.url] = list.value
                })
            })
        } else {
            // 如果有数据则直接完成load
            emit('loaded', list.value, (vals) => {
                list.value = vals
                appStore.urlSelectData[config.url] = list.value
            })
        }
    } else {
        // 缓存中不存在再调用接口 并且开始在缓存中打标记，以防止一个页面有相同接口时会调用多次
        appStore.urlSelectData[config.url] = []
        http({
            url: http.adornUrl(config.url),
            method: 'get',
            params: http.adornParams({})
        }).then(({ data }) => {
            let result = data.data
            if (config.convertData) {
                result = config.convertData(data.data)
            }
            list.value = handleData(result)
            appStore.urlSelectData[config.url] = list.value

            emit('loaded', list.value, (vals) => {
                list.value = vals
                appStore.urlSelectData[config.url] = list.value
            })
        })
    }
})
</script>
<style lang="scss" scoped></style>